/*
 * Created on 01.11.2003
 */
package de.javakicker;

import java.io.*;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * The Class XmlFile.
 *
 * @author Till Krullmann
 */
public class XmlFile
{
	
	/** The db. */
	private static DocumentBuilder db;
	
	/** The tr. */
	private static Transformer tr;
	
	static
	{
		try
		{
			db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			tr = TransformerFactory.newInstance().newTransformer();
		}
		catch (ParserConfigurationException e)
		{ }
		catch (TransformerConfigurationException e)
		{ }
	}
	
	/**
	 * Read from string.
	 *
	 * @param s the s
	 * @return the document
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws SAXException the sAX exception
	 */
	public static Document readFromString(String s)
		throws IOException, SAXException
	{
		return db.parse(new org.xml.sax.InputSource(new StringReader(s)));
	}
	
	/**
	 * Read from file.
	 *
	 * @param f the f
	 * @return the document
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws SAXException the sAX exception
	 */
	public static Document readFromFile(File f)
		throws IOException, SAXException
	{
		return db.parse(f);
	}
	
	/**
	 * Read from file.
	 *
	 * @param uri the uri
	 * @return the document
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws SAXException the sAX exception
	 */
	public static Document readFromFile(String uri)
		throws IOException, SAXException
	{
		return db.parse(uri);
	}
	
	/**
	 * Creates the.
	 *
	 * @return the document
	 */
	public static Document create()
	{
		return db.newDocument();
	}
	
	/**
	 * Write to file.
	 *
	 * @param doc the doc
	 * @param f the f
	 * @throws TransformerException the transformer exception
	 */
	public static void writeToFile(Document doc, File f)
		throws TransformerException
	{
		tr.transform( new DOMSource(doc), new StreamResult(f) );
	}
	
	/**
	 * Write to file.
	 *
	 * @param doc the doc
	 * @param uri the uri
	 * @throws TransformerException the transformer exception
	 */
	public static void writeToFile(Document doc, String uri)
		throws TransformerException
	{
		tr.transform( new DOMSource(doc), new StreamResult(uri) );		
	}
	
	
	/**
	 * Write to string.
	 *
	 * @param doc the doc
	 * @return the string
	 * @throws TransformerException the transformer exception
	 */
	public static String writeToString(Document doc)
		throws TransformerException
	{
		StringWriter w = new StringWriter();
		tr.transform( new DOMSource(doc), new StreamResult(w));
		return w.toString();
	}

}
